﻿using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace KayakMes.Common
{
    /// <summary>
    /// 基础仓储类，继承自SqlSugar的SimpleClient
    /// </summary>
    /// <typeparam name="T">实体类型</typeparam>
    public class BaseReposiotry<T> : SimpleClient<T> where T : class, new()
    {
        /// <summary>
        /// 数据库客户端
        /// </summary>
        private readonly ISqlSugarClient db;

        /// <summary>
        /// 构造函数，初始化仓储
        /// </summary>
        /// <param name="db">数据库客户端实例</param>
        public BaseReposiotry(ISqlSugarClient db) : base(db)
        {
            this.db = db;
        }

        /// <summary>
        /// 添加实体
        /// </summary>
        /// <param name="t">要添加的实体</param>
        /// <returns>返回影响的行数</returns>
        public int Add(T t)
        {
            return db.Insertable(t).ExecuteCommand();
        }

        /// <summary>
        /// 更新实体
        /// </summary>
        /// <param name="t">要更新的实体</param>
        /// <returns>返回影响的行数</returns>
        public int Update(T t)
        {
            return db.Updateable(t).ExecuteCommand();
        }

        /// <summary>
        /// 删除实体
        /// </summary>
        /// <param name="t">要删除的实体</param>
        /// <returns>返回影响的行数</returns>
        public int Delete(T t)
        {
            return db.Deleteable(t).ExecuteCommand();
        }

        /// <summary>
        /// 获取所有实体
        /// </summary>
        /// <returns>返回查询对象</returns>
        public ISugarQueryable<T> GetAll()
        {
            return db.Queryable<T>();
        }

        /// <summary>
        /// 根据ID获取实体
        /// </summary>
        /// <param name="id">实体ID</param>
        /// <returns>返回实体对象</returns>
        public T GetModel(long id)
        {
            return db.Queryable<T>().InSingle(id);
        }

        /// <summary>
        /// 批量更新实体
        /// </summary>
        /// <param name="entities">要更新的实体列表</param>
        /// <returns>返回影响的行数</returns>
        public int UpdateRange(List<T> entities)
        {
            return db.Updateable(entities).ExecuteCommand();
        }
    }
}
